#!/usr/bin/Rscript
##########################################################################################
# Issue Ownership and Agenda Setting in the 2019 Swiss National Elections
##########################################################################################
# Description:
# Script for Figure 4A
##########################################################################################
# Content
##########################################################################################
# 1) Dependencies
# 2) Startup
# 3) Load Data
# 4) Data Processing
# 5) Figure 4
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(ggplot2)
library(stringr)
library(forcats)
library(showtext)
library(ggforce)
library(cowplot)
##########################################################################################
# 2) Startup
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)


# - load fonts used in plots
sysfonts::font_add_google("Montserrat", "Montserrat")
sysfonts::font_add_google("Roboto", "Roboto")

# - load ddl theme
suppressMessages(suppressWarnings(source('../ggplot_theme_ddl.R')))
# - pre-setup for figure 1
ddl_theme_2 <- theme(legend.position = "bottom", legend.title = element_blank(), 
                     strip.background = element_blank(), strip.text = element_text(color = "black"),
                     axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
                     axis.text.y = element_text(hjust=0, size = 16, color = "black"),
                     axis.ticks.y = element_blank(),
                     strip.text.x = element_text(size = 16, color = "black"),
                     axis.title = element_text(size = 16, color = "black"),
                     legend.text = element_text(size = 16, color = "black"),
                     plot.title = element_blank(),
                     plot.margin = unit(c(.5,.5,.5,.5), "cm"),
                     legend.key.size = unit(1.5,"line"),
                     legend.key = element_blank(),
                     axis.line.x = element_line(color="black", size = .5),
                     axis.line.y = element_line(color="black", size = .5),
                     panel.spacing.y = unit(2, "lines"),
                     panel.spacing.x = unit(.8, "lines")) 

# - set directory
setwd(pathName)
parent_path <- getwd()
##########################################################################################
# 3) Load Data
##########################################################################################
# - load irf data 
final_input_b <- readRDS("../var/onetime-structural-shock-irfs-results_all_big_jan_appendix.RDS")
##########################################################################################
# 4) Data Processing Figure 4
##########################################################################################
# - topic names for model selection
mod_name_nice <- c("Environment", "Gender", "Immigration", "Europe", "All Four")

#-----------------------------------------------------------------------------------------
# - get data for responsiveness plot of all topics together
all_opics_all <- final_input_b[[5]]
all_opics_all$topic <- mod_name_nice[5]
all_opics_all <- all_opics_all %>% dplyr::filter(week %in% c(1,2,3))
all_opics_all <- all_opics_all %>% dplyr::filter(out %in% c("Media_SMD", "Party_CVP_TW", "Party_FDP_TW", "Party_GLP_TW",
                                                            "Party_Grüne_TW", "Party_SP_TW", "Party_SVP_TW")) %>% 
                                   dplyr::filter(cov %in% c("Media_SMD", "Party_CVP_TW", "Party_FDP_TW", "Party_GLP_TW",
                                                             "Party_Grüne_TW", "Party_SP_TW", "Party_SVP_TW"))

# - relabel the outcomes so they fit/look better in the plot
all_opics_all$out <- recode(all_opics_all$out,
                            `Media_SMD` = "Newspapers",
                            `Party_CVP_TW` = "Tweets by CVP",
                            `Party_FDP_TW` = "Tweets by FDP",
                            `Party_GLP_TW` = "Tweets by GLP",
                            `Party_Grüne_TW` = "Tweets by Green Party",
                            `Party_SP_TW` = "Tweets by SP",
                            `Party_SVP_TW` = "Tweets by SVP")

# - relabel the covariates so they fit/look better in the plot
all_opics_all$cov <- recode(all_opics_all$cov,
                            `Media_SMD` = "Newspapers",
                            `Party_CVP_TW` = "Tweets by CVP",
                            `Party_FDP_TW` = "Tweets by FDP",
                            `Party_GLP_TW` = "Tweets by GLP",
                            `Party_Grüne_TW` = "Tweets by Green Party",
                            `Party_SP_TW` = "Tweets by SP",
                            `Party_SVP_TW` = "Tweets by SVP")


#-----------------------------------------------------------------------------------------
# - combine data from all four topics models
for(n in 1:(length(final_input_b)-1)){
  tmp <- final_input_b[[n]]
  tmp$topic <- mod_name_nice[n]
  
  if(n == 1){
    all_topics <- tmp
  } else if(n == 4){
    all_topics <- rbind(all_topics, tmp)
    all_topics <- all_topics %>% dplyr::filter(week %in% c(1,2,3))
    all_topics <- all_topics %>% dplyr::filter(out %in% c("Media_SMD","Party_FDP_TW","Party_GLP_TW", "Party_CVP_TW",
                                                          "Party_Grüne_TW","Party_SP_TW","Party_SVP_TW")) %>% 
      dplyr::filter(cov %in% c("Media_SMD","Party_FDP_TW","Party_GLP_TW", "Party_CVP_TW",
                               "Party_Grüne_TW","Party_SP_TW","Party_SVP_TW"))
    # - relabel the outcomes so they fit/look better in the plot
    all_topics$out <- recode(all_topics$out,
                             `Media_SMD` = "Newspapers",
                             `Party_CVP_TW` = "Tweets by CVP",
                             `Party_FDP_TW` = "Tweets by FDP",
                             `Party_GLP_TW` = "Tweets by GLP",
                             `Party_Grüne_TW` = "Tweets by Green Party",
                             `Party_SP_TW` = "Tweets by SP",
                             `Party_SVP_TW` = "Tweets by SVP")
    
    # - relabel the covariates so they fit/look better in the plot
    all_topics$cov <- recode(all_topics$cov,
                             `Media_SMD` = "Newspapers",
                             `Party_CVP_TW` = "Tweets by CVP",
                             `Party_FDP_TW` = "Tweets by FDP",
                             `Party_GLP_TW` = "Tweets by GLP",
                             `Party_Grüne_TW` = "Tweets by Green Party",
                             `Party_SP_TW` = "Tweets by SP",
                             `Party_SVP_TW` = "Tweets by SVP")
    
  } else {
    all_topics <- rbind(all_topics, tmp)
    rm(tmp)
  }
}

# - rename values for nicer plot of resposivness plot per topic
plot_resp_ii <- all_topics %>% filter(week == 1 & data_type == "Effect of a one time 10 percentage point attention increase at week 0") %>%
                               mutate(direction = paste0(cov, " -> ", out)) %>%
                               mutate(TOPIC = str_to_upper(topic)) %>% 
                               mutate(topic = fct_relevel(topic, "Environment", "Gender", "Europe", "Immigration")) %>%
                               mutate(topic_rev = fct_relevel(topic, "Immigration", "Europe", "Gender", "Environment"))


plot_resp_ii$cov <- as.factor(plot_resp_ii$cov)
levels(plot_resp_ii$cov)

plot_resp_ii$cov <- factor(plot_resp_ii$cov, level = c("Tweets by CVP","Tweets by FDP","Tweets by GLP","Tweets by Green Party","Tweets by SP", "Tweets by SVP",
                                                       "Newspapers"))

plot_resp_ii$issue_sal <- ifelse(plot_resp_ii$topic %in% c("Environment", "Gender"), "High", "Low")
##########################################################################################
# 5) Figure 4
##########################################################################################
# Effect of Parties on Media:
plot_pm <- plot_resp_ii %>% dplyr::filter(cov %in% c("Tweets by CVP","Tweets by FDP","Tweets by GLP", 
                                                     "Tweets by Green Party","Tweets by SP",
                                                     "Tweets by SVP")) %>%
  dplyr::filter(out %in% c("Newspapers")) 


plot_pm$cov <- recode(plot_pm$cov,
                      `Tweets by CVP` = "CVP   ",
                      `Tweets by FDP` = "FDP   ",
                      `Tweets by GLP` = "GLP   ",
                      `Tweets by Green Party`="Greens",
                      `Tweets by SP` =  "SP    ",
                      `Tweets by SVP` = "SVP   ")

level_order <- factor(plot_pm$cov, level = c("CVP   ",
                                             "FDP   ",
                                             "GLP   ",
                                             "Greens",
                                             "SP    ",
                                             "SVP   "))

par_media <- ggplot(data = plot_pm) +
                aes(x = level_order, y = pe, ymin = lwr, ymax = upr, 
                    group = topic_rev, color = topic, shape = topic) +
                geom_linerange(size = 1.8, position = position_dodge(width = 0.55), alpha = 0.4) +  
                geom_point(position = position_dodge(width = 0.55), size = 2.5) +
                geom_hline(aes(yintercept = 0), color = "black", linetype = 2, alpha = 0.75) +
                coord_flip() +
                labs (subtitle = "Parties -> Newspapers", #(Effect of a one-time 10-percentage-point-increase over next 7 days)
                      title = "Attention responsiveness:", #Attention responsiveness of newspapers on parties 
                      y = "Percentage points", x = "") +
                scale_x_discrete() +
                scale_y_continuous(breaks = c(-3,-2,-1,0,1,2,3,4,5,6)) +
                scale_color_manual(labels = c("Environment","Gender","Europe","Immigration"), 
                                   values = c("#009E73","#DD2461","#0072B2","#999999")) +
                scale_fill_manual(labels = c("Environment","Gender","Europe","Immigration"), 
                                  values = c("#009E73","#DD2461","#0072B2","#999999")) +
                scale_shape_manual(labels = c("Environment","Gender","Europe","Immigration"), 
                                   values = c(15,16,17,18)) +
                facet_wrap(~ issue_sal,  ncol = 2, nrow = 1, scales = "free_y", 
                           labeller = as_labeller(c(`High`="",`Low`=""))) + 
                ddl_theme(panel.grid.major = element_blank(),
                          panel.grid.minor = element_blank()) +
                ddl_theme_2 + 
                theme(plot.title = element_text(size = 16, color = "black", face = "bold"),
                      plot.subtitle = element_text(size = 16, color = "black", face = "bold"),
                      strip.text.x = element_blank(),
                      strip.background = element_blank(), 
                      strip.text = element_blank()) +
                guides(color = guide_legend(override.aes = list(size=2)))

ggsave(plot = par_media, filename = paste0("../images/figure_A5.pdf"),  width = 24, height = 16.5, device = cairo_pdf, units = "cm")
##########################################################################################